<?php

namespace plugin\coupon\app\api\controller;

use app\api\logic\CouponLogic;
use app\common\controller\BaseApiController;
use support\utils\LockUtil;

class CouponController extends BaseApiController
{
    protected $noNeedLogin = [
        'getCanReceive'
    ];

    protected function init()
    {
        parent::init();
        $this->logic = new CouponLogic();
    }

    /**
     * 获取可以领取的优惠券
     */
    public function getCanReceive()
    {
        $data = $this->logic->getCanReceive(request()->uid ?? 0);
        return $this->success($data);
    }

    /**
     * 领取
     */
    public function receive()
    {
        $coupon_id = input('coupon_id');
        if (!$coupon_id) {
            return $this->error('参数错误');
        }
        LockUtil::tryLock(sprintf("receive_coupon:%s:%s", request()->uid, $coupon_id), function () {
            $this->logic->transaction(function () {
                $this->logic->receive(request()->uid, input('coupon_id'));
            });
        });
        return $this->success();
    }

    /**
     * 我的卡券
     */
    public function myCoupon()
    {
        $data = $this->logic->getMyCoupon(request()->uid, $this->form);
        return $this->success($data);
    }

}
